﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Yunwei.Core.MVC
{
    public class UserInfo : IUserInfo
    {
        /// <summary>
        /// 用户所有的权限列表.
        /// </summary>
        public List<string> Permissions;

        /// <summary>
        /// 当前用户是否登录
        /// </summary>
        public bool IsLogin = true;

        /// <summary>
        /// 系统用户ID
        /// </summary>
        public string Id
        {
            get;
            set;
        }

        /// <summary>
        /// 系统用户名称
        /// </summary>
        public string Name
        {
            get;
            set;
        }

        /// <summary>
        /// 系统用户登录帐号
        /// </summary>
        public string LoginName
        {
            get;
            set;
        }

        /// <summary>
        /// 系统用户是否启用
        /// </summary>
        public int IsEnabled
        {
            get;
            set;
        }

        /// <summary>
        /// 是否是管理员
        /// </summary>
        public bool IsAdmin
        {
            get;
            set;
        }

        /// <summary>
        /// 当前登录的用户信息。
        /// </summary>
        public static UserInfo CurrentUser
        {
            get
            {
                UserInfo userInfo = null;
                if (HttpContext.Current != null && HttpContext.Current.Session != null)
                {
                    userInfo = (HttpContext.Current.Session["Yunwei_UserLogin"] as UserInfo);
                }
                if (userInfo == null)
                {
                    userInfo = new UserInfo();
                }
                return userInfo;
            }
        }

        public UserInfo()
        {
            this.Id = "-1";
            this.Name = "未登录";
            this.LoginName = "_unlogin";
            this.IsAdmin = false;
            this.Permissions = new List<string>();
            this.IsLogin = false;
        }

        /// <summary>
        /// 用户是否拥有某个权限
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool HasPermission(string name)
        {
            return this.IsAdmin || this.Permissions.Contains(name.ToLower().Trim());
        }

        public static string EncodePassword(string pwd, string halt = "")
        {
            byte[] bytes = Encoding.UTF8.GetBytes(pwd + halt);
            MD5 mD = new MD5CryptoServiceProvider();
            byte[] value = mD.ComputeHash(bytes);
            return BitConverter.ToString(value).Replace("-", "");
        }
    }
}
